<template>
  <div class="inventory-alerts">
    <Card title="库存预警" :bordered="false">
      <div class="alerts-header">
        <Row :gutter="16">
          <Col :span="8">
            <Input
              v-model:value="searchForm.keyword"
              placeholder="搜索资源名称、预警类型"
              allow-clear
              @change="handleSearch"
            />
          </Col>
          <Col :span="4">
            <Select
              v-model:value="searchForm.alertType"
              placeholder="预警类型"
              allow-clear
              @change="handleSearch"
            >
              <SelectOption value="LOW_STOCK">低库存</SelectOption>
              <SelectOption value="OVERSTOCK">积压</SelectOption>
              <SelectOption value="EXPIRING">即将过期</SelectOption>
              <SelectOption value="MAINTENANCE">需要维护</SelectOption>
            </Select>
          </Col>
          <Col :span="4">
            <Select
              v-model:value="searchForm.severity"
              placeholder="严重程度"
              allow-clear
              @change="handleSearch"
            >
              <SelectOption value="LOW">低</SelectOption>
              <SelectOption value="MEDIUM">中</SelectOption>
              <SelectOption value="HIGH">高</SelectOption>
              <SelectOption value="CRITICAL">紧急</SelectOption>
            </Select>
          </Col>
          <Col :span="8">
            <Space>
              <Button type="primary" @click="handleSearch">搜索</Button>
              <Button @click="handleReset">重置</Button>
              <Button type="primary" @click="openAlertRule('create')">
                新增预警规则
              </Button>
              <Button @click="exportAlerts">导出</Button>
            </Space>
          </Col>
        </Row>
      </div>

      <div class="alerts-overview">
        <Row :gutter="16">
          <Col :span="6">
            <Statistic
              title="总预警数"
              :value="overview.total"
              :value-style="{ color: '#1890ff' }"
            />
          </Col>
          <Col :span="6">
            <Statistic
              title="紧急预警"
              :value="overview.critical"
              :value-style="{ color: '#ff4d4f' }"
            />
          </Col>
          <Col :span="6">
            <Statistic
              title="高优先级"
              :value="overview.high"
              :value-style="{ color: '#faad14' }"
            />
          </Col>
          <Col :span="6">
            <Statistic
              title="已处理"
              :value="overview.resolved"
              :value-style="{ color: '#52c41a' }"
            />
          </Col>
        </Row>
      </div>

      <div class="alerts-content">
        <Table
          :columns="columns"
          :data-source="alertList"
          :loading="loading"
          :pagination="pagination"
          row-key="id"
          @change="handleTableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'alertType'">
              <Tag :color="getAlertTypeColor(record.alertType)">
                {{ getAlertTypeText(record.alertType) }}
              </Tag>
            </template>
            <template v-else-if="column.key === 'severity'">
              <Tag :color="getSeverityColor(record.severity)">
                {{ getSeverityText(record.severity) }}
              </Tag>
            </template>
            <template v-else-if="column.key === 'status'">
              <Tag :color="getStatusColor(record.status)">
                {{ getStatusText(record.status) }}
              </Tag>
            </template>
            <template v-else-if="column.key === 'action'">
              <Space>
                <Button type="link" size="small" @click="viewAlert(record)">
                  查看
                </Button>
                <Button type="link" size="small" @click="resolveAlert(record)">
                  处理
                </Button>
                <Button type="link" size="small" @click="editAlert(record)">
                  编辑
                </Button>
                <Button
                  type="link"
                  size="small"
                  danger
                  @click="deleteAlert(record)"
                >
                  删除
                </Button>
              </Space>
            </template>
          </template>
        </Table>
      </div>
    </Card>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';
import {
  Button,
  Card,
  Col,
  Input,
  message,
  Modal,
  Row,
  Select,
  SelectOption,
  Space,
  Statistic,
  Table,
  Tag,
} from 'ant-design-vue';

const loading = ref(false);
const alertList = ref<any[]>([]);
const total = ref(0);

const searchForm = reactive({
  keyword: '',
  alertType: '',
  severity: '',
});

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

const overview = reactive({
  total: 0,
  critical: 0,
  high: 0,
  resolved: 0,
});

const columns = [
  {
    title: '资源名称',
    dataIndex: 'resourceName',
    key: 'resourceName',
    width: 150,
  },
  {
    title: '预警类型',
    dataIndex: 'alertType',
    key: 'alertType',
    width: 120,
  },
  {
    title: '严重程度',
    dataIndex: 'severity',
    key: 'severity',
    width: 100,
  },
  {
    title: '预警内容',
    dataIndex: 'message',
    key: 'message',
    width: 200,
  },
  {
    title: '当前值',
    dataIndex: 'currentValue',
    key: 'currentValue',
    width: 100,
  },
  {
    title: '阈值',
    dataIndex: 'threshold',
    key: 'threshold',
    width: 100,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 150,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right',
  },
];

// 模拟数据
const mockAlerts = [
  {
    id: '1',
    resourceName: '温泉池',
    alertType: 'LOW_STOCK',
    severity: 'HIGH',
    message: '库存数量低于最小阈值',
    currentValue: '1',
    threshold: '2',
    status: 'ACTIVE',
    createTime: '2024-01-15 10:30:00',
  },
  {
    id: '2',
    resourceName: 'VIP包间',
    alertType: 'LOW_STOCK',
    severity: 'CRITICAL',
    message: '库存数量为0，需要紧急补充',
    currentValue: '0',
    threshold: '1',
    status: 'ACTIVE',
    createTime: '2024-01-15 09:15:00',
  },
  {
    id: '3',
    resourceName: '豪华套房',
    alertType: 'OVERSTOCK',
    severity: 'MEDIUM',
    message: '库存积压，建议促销',
    currentValue: '8',
    threshold: '5',
    status: 'ACTIVE',
    createTime: '2024-01-15 08:45:00',
  },
  {
    id: '4',
    resourceName: '数字会议室',
    alertType: 'MAINTENANCE',
    severity: 'LOW',
    message: '设备需要定期维护',
    currentValue: '正常',
    threshold: '30天',
    status: 'RESOLVED',
    createTime: '2024-01-14 16:20:00',
  },
];

// 加载数据
const loadData = async () => {
  loading.value = true;
  try {
    await new Promise((resolve) => setTimeout(resolve, 500));

    let filteredData = mockAlerts;

    if (searchForm.keyword) {
      filteredData = filteredData.filter(
        (item) =>
          item.resourceName.includes(searchForm.keyword) ||
          item.alertType.includes(searchForm.keyword),
      );
    }

    if (searchForm.alertType) {
      filteredData = filteredData.filter(
        (item) => item.alertType === searchForm.alertType,
      );
    }

    if (searchForm.severity) {
      filteredData = filteredData.filter(
        (item) => item.severity === searchForm.severity,
      );
    }

    const start = (pagination.current - 1) * pagination.pageSize;
    const end = start + pagination.pageSize;

    alertList.value = filteredData.slice(start, end);
    total.value = filteredData.length;
    pagination.total = total.value;

    // 更新概览数据
    updateOverview(filteredData);
  } catch (error) {
    console.warn('加载预警数据失败:', error);
    message.error('加载数据失败');
  } finally {
    loading.value = false;
  }
};

// 更新概览数据
const updateOverview = (data: any[]) => {
  overview.total = data.length;
  overview.critical = data.filter(
    (item) => item.severity === 'CRITICAL',
  ).length;
  overview.high = data.filter((item) => item.severity === 'HIGH').length;
  overview.resolved = data.filter((item) => item.status === 'RESOLVED').length;
};

// 搜索
const handleSearch = () => {
  pagination.current = 1;
  loadData();
};

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    keyword: '',
    alertType: '',
    severity: '',
  });
  handleSearch();
};

// 表格变化
const handleTableChange = (pag: any) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  loadData();
};

// 打开预警规则
const openAlertRule = (type: 'create' | 'edit', record?: any) => {
  message.info(`${type === 'create' ? '新增' : '编辑'}预警规则功能开发中...`);
};

// 查看预警
const viewAlert = (record: any) => {
  message.info(`查看预警"${record.resourceName}"功能开发中...`);
};

// 处理预警
const resolveAlert = (record: any) => {
  Modal.confirm({
    title: '确认处理',
    content: `确定要处理预警"${record.resourceName}"吗？`,
    onOk: async () => {
      try {
        message.success('预警已处理');
        loadData();
      } catch (error) {
        console.warn('处理失败:', error);
        message.error('处理失败');
      }
    },
  });
};

// 编辑预警
const editAlert = (record: any) => {
  message.info(`编辑预警"${record.resourceName}"功能开发中...`);
};

// 删除预警
const deleteAlert = (record: any) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除预警"${record.resourceName}"吗？`,
    onOk: async () => {
      try {
        message.success('预警已删除');
        loadData();
      } catch (error) {
        console.warn('删除失败:', error);
        message.error('删除失败');
      }
    },
  });
};

// 导出预警
const exportAlerts = () => {
  message.success('预警数据导出成功');
};

// 工具函数
const getAlertTypeColor = (type: string) => {
  const colors: Record<string, string> = {
    LOW_STOCK: 'red',
    OVERSTOCK: 'orange',
    EXPIRING: 'purple',
    MAINTENANCE: 'blue',
  };
  return colors[type] || 'default';
};

const getAlertTypeText = (type: string) => {
  const texts: Record<string, string> = {
    LOW_STOCK: '低库存',
    OVERSTOCK: '积压',
    EXPIRING: '即将过期',
    MAINTENANCE: '需要维护',
  };
  return texts[type] || type;
};

const getSeverityColor = (severity: string) => {
  const colors: Record<string, string> = {
    LOW: 'green',
    MEDIUM: 'blue',
    HIGH: 'orange',
    CRITICAL: 'red',
  };
  return colors[severity] || 'default';
};

const getSeverityText = (severity: string) => {
  const texts: Record<string, string> = {
    LOW: '低',
    MEDIUM: '中',
    HIGH: '高',
    CRITICAL: '紧急',
  };
  return texts[severity] || severity;
};

const getStatusColor = (status: string) => {
  const colors: Record<string, string> = {
    ACTIVE: 'red',
    RESOLVED: 'green',
    IGNORED: 'gray',
  };
  return colors[status] || 'default';
};

const getStatusText = (status: string) => {
  const texts: Record<string, string> = {
    ACTIVE: '活跃',
    RESOLVED: '已处理',
    IGNORED: '已忽略',
  };
  return texts[status] || status;
};

onMounted(() => {
  loadData();
});
</script>

<style scoped>
.inventory-alerts {
  padding: 20px;
}

.alerts-header {
  margin-bottom: 24px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
}

.alerts-overview {
  margin-bottom: 24px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
}

.alerts-content {
  margin-bottom: 24px;
}
</style>
